package com.uton.rfidcontroller.view.activity.write.prescan;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.uton.rfidcontroller.R;
import com.uton.rfidcontroller.common.GlobalConstants;
import com.uton.rfidcontroller.common.intent.IntentBuilder;
import com.uton.rfidcontroller.common.rfid.UfhData;
import com.uton.rfidcontroller.common.utils.Utils;
import com.uton.rfidcontroller.databinding.ActivityPreScanToWriteBinding;
import com.uton.rfidcontroller.view.activity.SettingActivity;
import com.uton.rfidcontroller.view.base.BaseActivity;
import com.uton.rfidcontroller.viewmodel.activity_model.PreScanToWriteActivityViewModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import io.reactivex.ObservableTransformer;

/**
 * Created by 王家宝 on 2017/10/16.
 * Email:639586819@qq.com
 * Tel:18241150668
 */

public class PreScanToWriteActivity extends BaseActivity<ActivityPreScanToWriteBinding, PreScanToWriteActivityViewModel> {
    private Timer timer;
    private boolean isCanceled = true;
    private boolean Scanflag = false;
    private static final int SCAN_INTERVAL = 10;
    private Handler mHandler;
    private MyAdapter myAdapter;
    private Map<String, Integer> data = new HashMap<>();
    private static final int MSG_UPDATE_LISTVIEW = 0;

    @BindView(R.id.lv_scan_to_write)
    ListView mListView;


    @Override
    protected int setLayout() {
        return R.layout.activity_pre_scan_to_write;
    }

    @Override
    protected void inject() {
        getBinding().setModel(getViewModel());
    }

    @Override
    protected String setTitle() {
        return getString(R.string.ui_input);
    }

    @Override
    protected void doSomething() {
    }

    @Override
    protected PreScanToWriteActivityViewModel setViewModel() {
        return new PreScanToWriteActivityViewModel() {
            @Override
            public void scanToWrite() {
                scan();
            }

            @Override
            public void beginInit() {
                //设置适配器
                myAdapter = new MyAdapter(PreScanToWriteActivity.this, new ArrayList(data.keySet()));
                mListView.setAdapter(myAdapter);
                mHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        switch (msg.what) {
                            case GlobalConstants.CODE_COMPLETE:
                                myAdapter.notifyDataSetChanged();
                                break;
                            case MSG_UPDATE_LISTVIEW:
                                data = UfhData.scanResult6c;
                                if (myAdapter == null) {
                                    myAdapter = new MyAdapter(PreScanToWriteActivity.this, new ArrayList(data.keySet()));
                                    mListView.setAdapter(myAdapter);
                                } else {
                                    myAdapter.mList = new ArrayList(data.keySet());
                                }
                                myAdapter.notifyDataSetChanged();
                                break;

                            default:
                                break;

                        }
                    }
                };

                mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        UfhData.Set_sound(false);
                        UfhData.setUfh_id(myAdapter.mList.get(i));
                        switch (getIntent().getIntExtra(GlobalConstants.EXTRA_INT_PARAM1, GlobalConstants.RFID_NOTHING)) {
                            case GlobalConstants.RFID_WRITE:
                                startActivityForResult(new IntentBuilder().from(PreScanToWriteActivity.this, FinalWriteActivity.class).
                                        setStringParam(GlobalConstants.EXTRA_STRING_PARAM1, getIntent().getStringExtra(GlobalConstants.EXTRA_STRING_PARAM1)).
                                        getIntent(), GlobalConstants.REQUEST_WANT_DATA);
                                break;
                            case GlobalConstants.RFID_READ:
                                startActivity(new IntentBuilder().from(PreScanToWriteActivity.this, FinalReadActivity.class).getIntent());
                                break;
                            default:
                                break;
                        }

                    }
                });

            }

            @Override
            public ObservableTransformer setObservable() {
                return compose(bindToLifecycle());
            }
        };
    }

    private void scan() {
        if (!UfhData.isDeviceOpen()) {
            Utils.showShortToast(getString(R.string.toast_not_open_device));
            startActivity(new IntentBuilder().from(PreScanToWriteActivity.this, SettingActivity.class).getIntent());
            return;
        }

        if (timer == null) {
            ///////////声音开关初始化
            UfhData.Set_sound(true);
            UfhData.SoundFlag = false;
            //////////
            if (myAdapter != null) {
                UfhData.scanResult6c.clear();
                myAdapter.mList.clear();
                myAdapter.notifyDataSetChanged();
                mHandler.removeMessages(MSG_UPDATE_LISTVIEW);
                mHandler.sendEmptyMessage(MSG_UPDATE_LISTVIEW);
            }

            isCanceled = false;
            timer = new Timer();
            //
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    if (Scanflag) {
                        return;
                    }
                    Scanflag = true;
                    UfhData.read6c();
                    mHandler.removeMessages(MSG_UPDATE_LISTVIEW);
                    mHandler.sendEmptyMessage(MSG_UPDATE_LISTVIEW);
                    Scanflag = false;
                }
            }, 0, SCAN_INTERVAL);
            getViewModel().scanState.set(getString(R.string.ui_stop_scan));
        } else {
            //cancelScan();
            isCanceled = true;
            if (timer != null) {
                timer.cancel();
                timer = null;
                getViewModel().scanState.set(getString(R.string.ui_begin_scan));
            }
            UfhData.Set_sound(false);
        }

    }

    private void cancelScan() {
        isCanceled = true;
        mHandler.removeMessages(MSG_UPDATE_LISTVIEW);
        if (timer != null) {
            timer.cancel();
            timer = null;
            getViewModel().scanState.set(Utils.getString(R.string.ui_begin_scan));
            UfhData.scanResult6c.clear();
            if (myAdapter != null) {
                myAdapter.mList.clear();
                myAdapter.notifyDataSetChanged();
            }
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        UfhData.Set_sound(false);
        cancelScan();
    }


    class MyAdapter extends BaseAdapter {

        private Context mContext;
        private List<String> mList;
        private LayoutInflater layoutInflater;

        public MyAdapter(Context context, List<String> list) {
            mContext = context;
            mList = list;
            layoutInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return mList.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return mList.get(position);
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getView(int position, View view, ViewGroup viewParent) {
            // TODO Auto-generated method stub
            ItemView iv = null;
            if (view == null) {
                iv = new ItemView();
                view = layoutInflater.inflate(R.layout.item_scan_to_write, null);
                iv.tvCode = (TextView) view.findViewById(R.id.list_lable);
                iv.tvNum = (TextView) view.findViewById(R.id.list_number);
                view.setTag(iv);
            } else {
                iv = (ItemView) view.getTag();
            }
            iv.tvCode.setText(mList.get(position));
            iv.tvNum.setText(data.get(mList.get(position)).toString());
            return view;
        }

        public class ItemView {
            TextView tvCode;
            TextView tvNum;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case GlobalConstants.RESULT_IS_WRITE_SUCCESS:
                Intent intent = new Intent();
                intent.putExtra(GlobalConstants.IS_WRITE_IN_SUCCESS, data.getBooleanExtra(GlobalConstants.IS_WRITE_IN_SUCCESS, false));
                intent.putExtra(GlobalConstants.TID_NUM, data.getStringExtra(GlobalConstants.TID_NUM));
                setResult(GlobalConstants.RESULT_IS_WRITE_SUCCESS, intent);
                finish();
                break;
            default:
                break;
        }
    }
}
